

// file download

export const getFileName = (val: string): string => {
  const raw = decodeURIComponent(val);

  const matcher = raw.match(/filename[.*?]*=(.*?\.\w+)+/);
  // 不去捕获错误，目的没有达到
  return matcher[1];
};

export function downloadFile(data: Blob, filename?: string, header?: ServiceStructure["fetch"]["headers"]) {
  let fileName = filename;

  if (typeof fileName !== "string") {
    const t = header.get("content-disposition");
    fileName = getFileName(t);
  }

  if (typeof fileName !== "string") {
    fileName = "file";
  }

  const url = URL.createObjectURL(data);
  const a = document.createElement("a");
  a.download = fileName;
  a.href = url;
  a.click();

  const id = setTimeout(() => {
    clearTimeout(id);
    URL.revokeObjectURL(url);
    a.remove();
  });
}

export async function downloadFileFromStream(stream: Promise<ServiceStructure>, fileName?: string) {
  const rsp = await stream;
  return downloadFile(rsp.data, fileName, rsp.fetch.headers);
}


export async function downloadFileFromBlob(stream: Promise<Blob>, fileName: string) {
  const rsp = await stream;
  return downloadFile(rsp, fileName);
}


export function downloadFileFromurl(url: string, fileName: string) {
  return fetch(url)
    .then(rs => rs.blob())
    .then(r => downloadFile(r, fileName));
}


export { };
